package com.zyy.study.JUC;

import org.junit.Test;

import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo {
    public static void main(String[] args) {

    }

    @Test
    public void testFibonacci() {
        Fibonacci fibonacci = new Fibonacci(10);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        Integer result = forkJoinPool.invoke(fibonacci);
        System.out.println(result);
    }

    @Test
    public void testQuickSort() {
        int[] array = {2, 3, 5, 2, 1, 5, 7, 83, 2, 5987, 4, 0, 12, 54};
        quickSort quickSort = new quickSort(array, 0, array.length - 1);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        forkJoinPool.invoke(quickSort);
        System.out.println(Arrays.toString(array));//[0, 1, 2, 2, 2, 3, 4, 5, 5, 7, 12, 54, 83, 5987]
    }
}


class Fibonacci extends RecursiveTask<Integer> {
    public Fibonacci(Integer n) {
        this.n = n;
    }

    private Integer n;

    @Override
    protected Integer compute() {
        if (n <= 1) {
            return n;
        }
        Fibonacci fibonacci1 = new Fibonacci(n - 1);
        Fibonacci fibonacci2 = new Fibonacci(n - 2);
        fibonacci1.fork();
        fibonacci2.fork();
        return fibonacci1.join() + fibonacci2.join();
    }
}

class quickSort extends RecursiveAction {

    private int[] array;
    private int min;
    private int max;

    public quickSort(int[] array, int min, int max) {
        this.array = array;
        this.min = min;
        this.max = max;
    }

    @Override
    protected void compute() {
        if (min >= max) {
            return;
        }
        int index = array[min];
        int i = min;
        int j = max;
        while (i < j) {
            while (i < j && array[j] >= index) {
                j--;
            }
            while (i < j && array[i] <= index) {
                i++;
            }
            int tmp = array[j];
            array[j] = array[i];
            array[i] = tmp;
        }
        int tmp = array[i];
        array[i] = array[min];
        array[min] = tmp;

        quickSort quickSort1 = new quickSort(array, min, i - 1);
        quickSort quickSort2 = new quickSort(array, i + 1, max);
        quickSort1.fork();
        quickSort2.fork();
        quickSort1.join();
        quickSort2.join();

    }
}
